package com.oceansoft.mobile.weixin.core;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.oceansoft.mobile.weixin.entity.WXOauth2Token;
import com.oceansoft.mobile.weixin.entity.WX_SNS_User;
import com.oceansoft.mobile.weixin.util.WeixinUtil;
  
  
/** 
 * 核心请求处理类 
 */
@Controller
@RequestMapping("oauthServlet")
public class OAuthServlet{
	
	/** 
	 * 微信授权通用写法
     * 确认请求来自微信服务器 
     */  
	@RequestMapping("oauth.do")
    public void doGet(HttpServletRequest request, HttpServletResponse response,HttpSession session){  
    	try {
			request.setCharacterEncoding("gb2312");
			response.setCharacterEncoding("gb2312");
			String code=request.getParameter("code");
			String state=request.getParameter("state");
			if(!"authdeny".equals(code)){
				WXOauth2Token oa=WeixinUtil.getOauth2AccessToken(WeixinUtil.APPID, WeixinUtil.SECRET, code);
				String accessToken=oa.getAccessToken();
				String openId=oa.getOpenId();
				WX_SNS_User user=WeixinUtil.getSNSUserInfo(accessToken, openId);
				request.setAttribute("snsUser", user);
			}
			request.getRequestDispatcher("/lohas/index").forward(request, response);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }  
    
}   